package board;

import java.net.*;
import java.util.*;

import javax.servlet.http.*;

import model.*;
import community.*;

import org.apache.struts.action.*;
import org.apache.struts.actions.*;

import community.*;

import util.*;

public class FreeBoardAction extends DispatchAction {

	/**
	 * Default List Print
	 * */
	public ActionForward getList(ActionMapping mapping, ActionForm form, 
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		FreeForm freeform = (FreeForm)form;
				
		int cono = 0;
		String fbname = null;
		
		if(!freeform.getCono().equals("")||freeform.getCono()!=null) {
			cono = Integer.parseInt(request.getParameter("cono"));
			freeform.setCono(cono+"");
		} else {
			cono = Integer.parseInt(freeform.getCono());			
		}
		
//		Generate menu element on session
		if(cono<10){
			Menu menu = new Menu();
			if(cono!=2) menu = this.setMainMenu(menu);
			else menu.setFreeBoardMenus(this.getFreeboardMenus(cono));			
			request.getSession().setAttribute("menu", menu);
		} else {
			CommunityGo.setMemberCommunity(request);
		}
			
		if(!freeform.getFbname().equals("")) {
			
			fbname = URLDecoder.decode(request.getParameter("fbname"),"utf-8");
			
			freeform.setFbname(fbname);
			
		} else {
			fbname = freeform.getFbname();
		}
		
		Pager pager = new Pager();
		
		FreeBoard fb = new FreeBoard();
		
		fb.setCono(cono);
		fb.setFbname(fbname);
		
		FreeBoardDAO fbDAO = new FreeBoardDAO();
		
//		게시물 리스트 추출 & 검색
		String search = request.getParameter("search");
		String keyword = request.getParameter("word");
		String words = null;
		Vector<FreeBoard> list = null;
		if(search!=null) {
//			request.getSession().setAttribute("word", URLDecoder.decode(request.getParameter("word"),"utf-8"));
			System.out.println("키워드 : "+keyword);
			if(keyword==null) {
				words =(String)request.getSession().getAttribute("word"); 
			} else {
				words = keyword;
				request.getSession().setAttribute("word", keyword);
			}
			
			System.out.println("검색 분류 : "+search);
			System.out.println("검색단어 : "+words);
			if(search.equals("snick")){
				System.out.println("아이디 검색으로 이동...by "+words);
				String nick = words;
				
				String word = MemberCommunityDAO.getCommunityMid(nick, cono);			
				long totalRows = FreeBoardDAO.getTotalRowsByMid(word, cono, fbname);
				System.out.println("tRows :" + totalRows);
				pager.init(request, totalRows, 10, 5);				
				//@@ list = fbDAO.getBoardListPage(fb, pager.getCurrentPage(), pager.getRowsPerPage(), word!=null?word:nick,"mid",totalRows);
				list = fbDAO.getBoardListPage(fb, pager.getCurrentPage(), pager.getRowsPerPage(), word!=null?word:nick,"mid",totalRows);//##
			} else if(search.equals("stitle")){
				System.out.println("제목 검색으로 이동...by "+words);
//				String word = URLDecoder.decode(request.getParameter("word"),"utf-8");			
				String word = words;
				long totalRows = FreeBoardDAO.getTotalRowsByTitle(word, cono, fbname);				
				pager.init(request, totalRows, 10, 5);
				//@@ list = fbDAO.getBoardListPage(fb, pager.getCurrentPage(), pager.getRowsPerPage(), word,"fbtitle",totalRows);
				list = fbDAO.getBoardListPage(fb, pager.getCurrentPage(), pager.getRowsPerPage(), word,"fbtitle",totalRows);//##
			}
			
		} else if(search==null||search.equals("")){
			System.out.println("전체목록 검색으로 이동...");
			long totalRows = fbDAO.getTotalRows(fb);
			pager.init(request, totalRows, 10, 5);
			list = fbDAO.getBoardListPage(fb, pager.getCurrentPage(), pager.getRowsPerPage());
			request.getSession().setAttribute("word", null);
		} 
		
		
		
		
		ArrayList<FreeForm> freelists = new ArrayList<FreeForm>();
		for(FreeBoard freeb : list){
			FreeForm ff = new FreeForm();
			
			ff = this.castBoardToForm(ff, freeb);
						
			freelists.add(ff);
		}
//		
		freeform.setCono(fb.getCono()+"");
		freeform.setFbname(fb.getFbname());
		freeform.setFreelists(freelists);
		
//		set nickname for each community
		User user = (User)request.getSession().getAttribute("user");
		String mcnick = MemberCommunityDAO.getCommunityNick(user.getMid(), cono);		
		user.setMcnick(mcnick);
		request.getSession().setAttribute("user", user);
		request.getSession().setAttribute("pager", pager);
		
		return mapping.findForward("freelist");
	}
	


	public ActionForward delete(ActionMapping mapping, ActionForm form, 
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		FreeForm ff = (FreeForm)form;		
		Long fbno = Long.parseLong(ff.getFbno());
		FreeBoardDAO fbDAO = new FreeBoardDAO();
		FreeCommentDAO fcDAO = new FreeCommentDAO();
		
		fcDAO.deleteAll(fbno);
		fbDAO.deleteReplies(fbno);
		fbDAO.delete(fbno);
						
		return getList(mapping,form,request,response);
	}
		
	public ActionForward insertform(ActionMapping mapping, ActionForm form, 
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		FreeForm ff = (FreeForm)form;		
		User user =(User)request.getSession().getAttribute("user");
		String mcnick = MemberCommunityDAO.getCommunityNick(user.getMid(), Integer.parseInt(ff.getCono()));
		String mid = user.getMid();
		
		ff.setMcnick(mcnick);
		ff.setMid(mid);
				
		return mapping.findForward("freeinsert");
	}
	
	public ActionForward insert(ActionMapping mapping, ActionForm form, 
			HttpServletRequest request, HttpServletResponse response) throws Exception {

		FreeForm ff = (FreeForm)form;
		
		FreeBoardDAO fbDAO = new FreeBoardDAO();
		FreeBoard fb = new FreeBoard();
		
		if(ff.getFbtitle().trim().length()<1) return mapping.findForward("freeinsert");
		if(ff.getFbcontent().trim().length()<1) return mapping.findForward("freeinsert");
		
		fb.setCono(Integer.parseInt(ff.getCono()));
		fb.setMid(ff.getMid());
		
		fb.setFbcontent(ff.getFbcontent());
		fb.setFbname(ff.getFbname());
		
		if(ff.getFbrefno()!="") {
			fb.setFbrefno(Integer.parseInt(ff.getFbrefno()));
			fb.setFbtitle("  └ "+ff.getFbtitle());
		} else {
			fb.setFbrefno(0);
			fb.setFbtitle(ff.getFbtitle());
		}
				
		if(fbDAO.insert(fb)){			
			return getList(mapping,form,request,response);
		} else {			
			return mapping.findForward("freeinsert");		
		}
	}
	
	public ActionForward updateform(ActionMapping mapping, ActionForm form, 
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		FreeForm ff = (FreeForm)form;		
		User user =(User)request.getSession().getAttribute("user");
		String mcnick = MemberCommunityDAO.getCommunityNick(user.getMid(), Integer.parseInt(ff.getCono()));
		String mid = user.getMid();
		
		ff.setMcnick(mcnick);
		ff.setMid(mid);
		
		return mapping.findForward("freeupdate");
	}

	public ActionForward update(ActionMapping mapping, ActionForm form, 
			HttpServletRequest request, HttpServletResponse response) throws Exception {

		FreeForm ff = (FreeForm)form;
		
		FreeBoardDAO fbDAO = new FreeBoardDAO();
		FreeBoard fb = new FreeBoard();
		
		User user =(User)request.getSession().getAttribute("user");
		String mid = user.getMid();
								
		ff.setMid(mid);
		
		if(ff.getFbtitle().trim().length()<1) return mapping.findForward("freeupdate");
		if(ff.getFbcontent().trim().length()<1) return mapping.findForward("freeupdate");
		
		fb.setFbno(Integer.parseInt(ff.getFbno()));
		
		fb.setMid(ff.getMid());
		fb.setFbtitle(ff.getFbtitle());
		fb.setFbcontent(ff.getFbcontent());
		
		if(fbDAO.updateFreeBoard(fb)){			
			return getList(mapping,form,request,response);
		} else {			
			return mapping.findForward("freeupdate");		
		}
	}
	
	/**
	 * DetailView
	 * */
	public ActionForward detailView(ActionMapping mapping, ActionForm form, 
			HttpServletRequest request, HttpServletResponse response) throws Exception {

		FreeForm ff = (FreeForm)form;
		User user = (User)request.getSession().getAttribute("user");
		Long fbno = Long.parseLong(request.getParameter("fbno"));
		FreeBoardDAO fbDAO = new FreeBoardDAO();
		
		FreeBoard freeb = fbDAO.getFreeBoard(fbno);	//getting FreeBoard Element

		FreeBoardAction.setMenu(freeb.getCono(), request);
		
		if(freeb!=null) {
			if(!user.getMid().equals(freeb.getMid())) fbDAO.updateReadCount(fbno);	//increase counter
			
//			setting FreeForm by FreeBoard
			ff = this.castBoardToForm(ff,freeb);
			long preview = fbDAO.getPreview(freeb);
			long next = fbDAO.getNext(freeb);
			
			FreeForm pForm = new FreeForm();
			FreeForm nForm = new FreeForm();
		
			ff.setRownum(fbDAO.getRownum(freeb.getCono(), freeb.getFbname(), fbno));
			System.out.println(fbno+"'s rownum : "+ff.getRownum());
		
//			setting preview and next articles
			if(preview<freeb.getFbno()) {
				ff.setPreview(this.castBoardToForm(pForm, fbDAO.getFreeBoard(preview)));				
			} else {
				ff.setPreview(null);
			}
			if(next>freeb.getFbno()){
				ff.setNext(this.castBoardToForm(nForm, fbDAO.getFreeBoard(next)));
			} else {
				ff.setNext(null);
			}
			
			return mapping.findForward("freeview");
		} else return getList(mapping,form,request,response);	//if DTO is null;				
	}

	
	public ActionForward setMenus(ActionMapping mapping, ActionForm form, 
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		 
		Menu menu = new Menu();
		if(request.getSession().getAttribute("membercommunity")!=null) request.getSession().setAttribute("membercommunity",null);
		
		menu.setFreeBoardMenus(this.getFreeboardMenus(2));
		
		request.getSession().setAttribute("menu", menu);
		
		ActionForward af = new ActionForward();
		af.setPath("/freemain.jsp");
		af.setRedirect(true);
		
		return af;
	}
	
	private static void setMenu(int cono, HttpServletRequest request){
	
		if(request.getSession().getAttribute("menu")==null){
			Menu menu = new Menu();
			
			menu.setFreeBoardMenus(getFreeboardMenus(cono));
			if(cono<10) {
//				menu.setCommLinkMenus(null);
				menu.setNoticeBoardMenus(NoticeBoardAction.setMainNoticeMenu());
//				menu.setDataBoardMenus(null);
//				menu.setPhotoBoardMenus(null);
					BoardNames bns = new BoardNames();
					bns.setBname("QnA 게시판");
					String url = "noticeboard.do?method=list&qbname=";
					bns.setUrl(url);
				menu.setQnaBoardMenu(bns);
			}
			request.getSession().setAttribute("menu", menu);
		}
		
		
	}
	
	/**
	 * DTO to ActionForm (FreeForm)
	 * */
	public static FreeForm castBoardToForm(FreeForm ff, FreeBoard fb){
			
		ff.setCono(fb.getCono()+"");
		ff.setFbname(fb.getFbname());
		ff.setMid(fb.getMid());
		ff.setFbcontent(fb.getFbcontent());
		ff.setFbdate(fb.getFbdate());
		ff.setFbsdate(fb.getFbdate().substring(0, 10));
		ff.setFbcounter(fb.getFbcounter()+"");
		ff.setFbno(fb.getFbno()+"");
		ff.setFbtitle(fb.getFbtitle());
		ff.setFbrefno(fb.getFbrefno()+"");	
		ff.setRownum(fb.getRownum()+"");
		ff.setFbcomments(fb.getFbcomments()+"");
		
		
		
		String mcnick = MemberCommunityDAO.getCommunityNick(fb.getMid(), fb.getCono());
		ff.setMcnick(mcnick!=null?mcnick:fb.getMid());
		
		return ff;		
	}
	
	/*
	public static FreeBoard castFormToBoard(FreeForm ff){
		FreeBoard fb = new FreeBoard();
		
		return fb;
	}
	*/
	
	public static Vector getFreeboardMenus(int cono) {
		 
			
		Vector<BoardNames> v = new Vector<BoardNames>();
		
		String url = "freeboard.do?method=getList&cono="+cono+"&fbname=";
		
		FreeBoardDAO fbDAO = new FreeBoardDAO();
		String[] bnames = fbDAO.getBoardMenus(cono);
		
		for(int i=0;i<bnames.length;i++){
			BoardNames bns = new BoardNames();
			bns.setBname(bnames[i]);
			bns.setUrl(url);
			v.add(bns);
		}		
		return v;
	}
	
	public boolean createNewBoard(int cono, String fbname, String mid){
		
		FreeBoard fb = new FreeBoard();
		fb.setMid(mid);
		fb.setCono(cono);
		fb.setFbcontent("게시판 생성용 게시물");
		fb.setFbtitle("게시판 생성");
		fb.setFbname(fbname);
		fb.setFbrefno(0);
		
		FreeBoardDAO fbDAO = new FreeBoardDAO();
		if(fbDAO.insert(fb)) return true;
		else return false;
	}
	
	public boolean changeBoardName(int cono, String fbname, String newname){
		
		FreeBoardDAO fbDAO = new FreeBoardDAO();
		System.out.println(fbDAO.setBoardName(cono, fbname,newname));
		
		return false;
	}
	
	public static void main(String[] args){
		FreeBoardAction fba = new FreeBoardAction();
		fba.createNewBoard(2, "아나바다 게시판", "aijua");
		
	}

	public ActionForward getMain(ActionMapping mapping, ActionForm form, 
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		User user = (User)request.getSession().getAttribute("user");
		user.setCono(7+"");
		user.setMcnick(user.getMid());
		Menu menu = new Menu();
		menu = this.setMainMenu(menu);

		request.getSession().setAttribute("menu", menu);
		System.out.println("메인게시판세팅완료...............");
		
		return mapping.findForward("boardmain");
	}
	
	public static Menu setMainMenu(Menu menu){
		
//		공지사항 세팅
		BoardNames nbns1 = new BoardNames();
		nbns1.setBname("공지사항");
		nbns1.setUrl("noticeboard.do?method=getList&cono=6&nbname=");
		
		BoardNames nbns2 = new BoardNames();
		nbns2.setBname("ITEA 뉴스");
		nbns2.setUrl("noticeboard.do?method=getList&cono=8&nbname=");
		
		
		Vector<BoardNames> nv = new Vector<BoardNames>();
		nv.add(nbns1);
		nv.add(nbns2);
		menu.setNoticeBoardMenus(nv);
		
		
//		자유게시판 세팅
		BoardNames fbns = new BoardNames();
		FreeBoardDAO fbDAO = new FreeBoardDAO();
		String[] fbnames = fbDAO.getBoardMenus(5);
		String furl = "freeboard.do?method=getList&cono=5&fbname=";
		Vector<BoardNames> fv = new Vector<BoardNames>();
		for(String fb : fbnames){
			fbns.setBname(fb);
			fbns.setUrl(furl);
			fv.add(fbns);			
		}
		
//		QnA 게시판 세팅
		BoardNames qbns = new BoardNames();
		qbns.setBname("QnA 게시판");
		qbns.setUrl("qnaboard.do?method=list&qbname=");
		
		menu.setFreeBoardMenus(fv);
		menu.setQnaBoardMenu(qbns);
				
		return menu;
	}
	
	
	
}
